import { app, BrowserWindow, ipcMain, dialog } from 'electron';
import * as path from 'path';
import { execFile } from 'child_process';
import { promisify } from 'util';
import * as fs from 'fs/promises';
import { scanDevices as scanDevicesAdb, sendFileToDevice, executeScript } from './adbTest';
import { WebSocket, WebSocketServer } from 'ws';
import { AddressInfo } from 'net';

const execFileAsync = promisify(execFile);
const adbPath = 'D:\\software\\android_sdk\\platform-tools\\adb.exe';

// 当前打开的文件路径
let currentFilePath: string | null = null;

let mainWindow: BrowserWindow;
let wsServer: WebSocketServer | null = null;
const connectedDevices = new Map<string, WebSocket>();

async function scanDevices() {
  try {
    const { stdout } = await execFileAsync(adbPath, ['devices', '-l']);
    console.log('ADB输出:', stdout);
    
    const lines = stdout.split('\n').slice(1); // 跳过第一行的 "List of devices attached"
    const devices = lines
      .map(line => line.trim())
      .filter(line => line.length > 0)
      .map(line => {
        const [id, ...rest] = line.split(' ');
        const modelMatch = rest.join(' ').match(/model:(\S+)/);
        return {
          id,
          model: modelMatch ? modelMatch[1] : '未知设备',
          status: 'online'
        };
      });

    return devices;
  } catch (error) {
    console.error('执行ADB命令出错:', error);
    return [];
  }
}

// 创建WebSocket服务器
function createWebSocketServer(port: number = 0) {
  if (wsServer) {
    return;
  }

  wsServer = new WebSocketServer({ port });
  
  wsServer.on('listening', () => {
    const address = wsServer!.address() as AddressInfo;
    console.log(`WebSocket服务器启动在端口: ${address.port}`);
    // 通知渲染进程WebSocket服务器已启动
    mainWindow?.webContents.send('ws-server-started', { port: address.port });
  });

  wsServer.on('connection', (ws: WebSocket) => {
    console.log('新的WebSocket连接');
    
    // 等待设备发送标识信息
    ws.once('message', (data) => {
      try {
        const deviceInfo = JSON.parse(data.toString());
        if (deviceInfo.type === 'device-info') {
          const deviceId = deviceInfo.deviceId;
          console.log('设备连接:', deviceId);
          
          // 存储设备连接
          connectedDevices.set(deviceId, ws);
          
          // 通知渲染进程设备已连接
          mainWindow?.webContents.send('device-connected', {
            deviceId,
            model: deviceInfo.model,
            isWebSocket: true
          });
          
          // 监听设备断开连接
          ws.on('close', () => {
            console.log('设备断开连接:', deviceId);
            connectedDevices.delete(deviceId);
            mainWindow?.webContents.send('device-disconnected', { deviceId });
          });
          
          // 监听设备消息
          ws.on('message', (message) => {
            try {
              const data = JSON.parse(message.toString());
              if (data.type === 'script-result') {
                mainWindow?.webContents.send('script-result', {
                  deviceId,
                  ...data
                });
              }
            } catch (error) {
              console.error('解析设备消息失败:', error);
            }
          });
        }
      } catch (error) {
        console.error('解析设备信息失败:', error);
        ws.close();
      }
    });
  });

  wsServer.on('error', (error) => {
    console.error('WebSocket服务器错误:', error);
    mainWindow?.webContents.send('ws-server-error', { error: error.message });
  });
}

// 停止WebSocket服务器
function stopWebSocketServer() {
  if (wsServer) {
    // 关闭所有连接
    for (const [deviceId, ws] of connectedDevices) {
      ws.close();
      mainWindow?.webContents.send('device-disconnected', { deviceId });
    }
    connectedDevices.clear();

    // 关闭服务器
    wsServer.close(() => {
      console.log('WebSocket服务器已停止');
      wsServer = null;
    });
  }
}

// 通过WebSocket执行脚本
async function executeScriptViaWebSocket(deviceId: string, script: string): Promise<void> {
  const ws = connectedDevices.get(deviceId);
  if (!ws) {
    throw new Error('设备未通过WebSocket连接');
  }
  
  ws.send(JSON.stringify({
    type: 'run-script',
    script
  }));
}

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js')
    }
  });

  // 开发环境下打开开发者工具
  mainWindow.webContents.openDevTools();

  // 加载HTML文件
  mainWindow.loadFile(path.join(__dirname, '../../public/index.html'));
  
  // 创建WebSocket服务器
  createWebSocketServer();
}

// 设置IPC处理程序
ipcMain.handle('test', async () => {
  return 'preload测试成功';
});

// 设备扫描相关IPC处理
ipcMain.handle('scan-devices', async () => {
  try {
    const devices = await scanDevicesAdb();
    // 合并ADB设备和WebSocket设备
    const allDevices = devices.map(device => ({
      ...device,
      isWebSocket: false
    }));
    
    // 添加WebSocket连接的设备
    connectedDevices.forEach((_, deviceId) => {
      if (!allDevices.some(d => d.id === deviceId)) {
        allDevices.push({
          id: deviceId,
          model: '通过WebSocket连接',
          isWebSocket: true
        });
      }
    });
    
    return { success: true, devices: allDevices };
  } catch (error: any) {
    console.error('扫描设备失败:', error);
    return { success: false, error: error.message || '未知错误' };
  }
});

// 文件操作处理程序
ipcMain.handle('dialog:openFile', async () => {
  const { canceled, filePaths } = await dialog.showOpenDialog({
    filters: [
      { name: 'JavaScript', extensions: ['js'] },
      { name: 'All Files', extensions: ['*'] }
    ],
    properties: ['openFile']
  });

  if (!canceled && filePaths.length > 0) {
    const filePath = filePaths[0];
    try {
      const content = await fs.readFile(filePath, 'utf-8');
      currentFilePath = filePath;
      return { filePath, content };
    } catch (err) {
      console.error('读取文件失败:', err);
      throw new Error('读取文件失败');
    }
  }
  return null;
});

ipcMain.handle('dialog:saveFile', async (event, content: string) => {
  if (currentFilePath) {
    try {
      await fs.writeFile(currentFilePath, content, 'utf-8');
      return { success: true, filePath: currentFilePath };
    } catch (err) {
      console.error('保存文件失败:', err);
      throw new Error('保存文件失败');
    }
  } else {
    return handleSaveFileAs(content);
  }
});

// 添加一个辅助函数来处理另存为操作
async function handleSaveFileAs(content: string) {
  const { canceled, filePath } = await dialog.showSaveDialog({
    filters: [
      { name: 'JavaScript', extensions: ['js'] },
      { name: 'All Files', extensions: ['*'] }
    ]
  });

  if (!canceled && filePath) {
    try {
      await fs.writeFile(filePath, content, 'utf-8');
      currentFilePath = filePath;
      return { success: true, filePath };
    } catch (err) {
      console.error('保存文件失败:', err);
      throw new Error('保存文件失败');
    }
  }
  return { success: false };
}

ipcMain.handle('dialog:saveFileAs', async (event, content: string) => {
  return handleSaveFileAs(content);
});

// 添加文件传输处理程序
ipcMain.handle('adb:sendFile', async (event, deviceId: string, sourcePath: string, targetPath: string) => {
  try {
    let progressWindow: BrowserWindow | null = null;
    
    // 创建进度窗口
    progressWindow = new BrowserWindow({
      width: 300,
      height: 150,
      frame: false,
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false
      }
    });

    // 加载进度显示页面
    progressWindow.loadFile(path.join(__dirname, '../../public/progress.html'));

    // 发送文件并更新进度
    await sendFileToDevice(deviceId, sourcePath, targetPath, (progress) => {
      if (progressWindow) {
        progressWindow.webContents.send('update-progress', progress);
      }
      
      // 传输完成时关闭进度窗口
      if (progress === 100 && progressWindow) {
        setTimeout(() => {
          progressWindow?.close();
          progressWindow = null;
        }, 1000);
      }
    });

    return { success: true };
  } catch (error) {
    console.error('文件传输失败:', error);
    throw error;
  }
});

// 文件传输相关IPC处理
ipcMain.handle('send-file', async (event, { deviceId, filePath, fileName }) => {
  try {
    await sendFileToDevice(deviceId, filePath, fileName, (progress) => {
      // 发送进度更新到渲染进程
      event.sender.send('file-transfer-progress', {
        deviceId,
        filePath,
        progress
      });
    });
    return { success: true };
  } catch (error: any) {
    console.error('文件传输失败:', error);
    return { success: false, error: error.message || '未知错误' };
  }
});

// 脚本执行相关IPC处理
ipcMain.handle('execute-script', async (event, { deviceId, scriptContent }) => {
  try {
    // 检查是否是WebSocket连接的设备
    if (connectedDevices.has(deviceId)) {
      await executeScriptViaWebSocket(deviceId, scriptContent);
    } else {
      await executeScript(deviceId, scriptContent);
    }
    return { success: true };
  } catch (error: any) {
    console.error('脚本执行失败:', error);
    return { success: false, error: error.message || '未知错误' };
  }
});

// WebSocket服务器管理
ipcMain.on('start-ws-server', (event, { port }) => {
  createWebSocketServer(port);
});

ipcMain.on('stop-ws-server', () => {
  stopWebSocketServer();
});

ipcMain.on('get-ws-server-status', (event) => {
  if (wsServer) {
    const address = wsServer.address() as AddressInfo;
    event.reply('ws-server-started', { port: address.port });
  }
});

app.whenReady().then(() => {
  createWindow();

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// 清理WebSocket服务器
app.on('before-quit', () => {
  if (wsServer) {
    wsServer.close();
  }
});



